package apps.sim.http;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.util.Map;

import apps.sim.proxy.ProxyServer;
import apps.sim.proxy.SocketAddressResolver;

import com.sun.net.httpserver.HttpExchange;

public class HttpSettingsHandler extends HttpBaseHandler {
	public static ProxyServer proxyServer = new ProxyServer();

	public static void initState() {
		try {
			final String string = readFile();
			final StringReader stringReader = new StringReader(string);
			final BufferedReader br = new BufferedReader(stringReader);
			String line;
			while ((line = br.readLine()) != null) {
				if (line.contains("enable-proxy")) {
					final int start = line.indexOf(">");
					final int end = line.indexOf("<", start);
					final String value = line.substring(start + 1, end);
					if (value.equals("true")) {
						startProxy();
					}
				} else if (line.contains("auto-redirect")) {
					final int start = line.indexOf(">");
					final int end = line.indexOf("<", start);
					final String value = line.substring(start + 1, end);
					if (value.equals("true")) {
						ProxyServer.FLAG_RESOLVE_ADDRESSES = true;
					}
				}

			}
			if (string.contains("url-mappings")) {
				final String str = "<url-mappings>";
				final int start = string.indexOf(str);
				final int end = string.indexOf("</url-mappings>", start);
				final String value = string.substring(start + str.length(), end);
				SocketAddressResolver.setMappings(value);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void execute(HttpExchange exchange) throws Exception {
		final Map<String, String> extractParams = extractParams(exchange.getRequestURI());
		if (extractParams.keySet().contains("retrieve")) {
			final String string = readFile();
			successResponse(exchange, new ByteArrayInputStream(string.getBytes()), "text/xml;charset=utf-8");
		} else if (extractParams.keySet().contains("save")) {
			writeToFile(extractParams);
			successResponse(exchange, new ByteArrayInputStream("<html>Data Saved..</html>".getBytes()));
		}

	}

	private static String readFile() throws Exception {
		final File file = getSettingFile();
		final StringBuilder builder = new StringBuilder();

		if (file.exists()) {
			final FileReader fileReader = new FileReader(file);
			int i = 0;
			while ((i = fileReader.read()) != -1) {
				builder.append((char) i);
			}
			fileReader.close();
		}
		return builder.toString();
	}

	private void writeToFile(final Map<String, String> extractParams) throws IOException {
		boolean startProxy = false;
		boolean enableFiltering = false;
		final StringBuilder builder = new StringBuilder();
		builder.append("<shycop-settings>");
		builder.append("\n");
		builder.append("<enable-proxy>");
		final String proxy = extractParams.get("proxy");
		startProxy = proxy != null && !proxy.equals("") ? true : false;
		builder.append(startProxy);
		builder.append("</enable-proxy>");
		builder.append("\n");
		builder.append("<auto-redirect>");
		final String redirect = extractParams.get("autoRedirect");
		enableFiltering = redirect != null && !redirect.equals("") ? true : false;
		builder.append(enableFiltering);
		builder.append("</auto-redirect>");
		builder.append("\n");
		builder.append("<url-mappings>");
		final String urlMappings = extractParams.get("urlMappings");
		SocketAddressResolver.setMappings(urlMappings);
		builder.append(urlMappings);
		builder.append("</url-mappings>");
		builder.append("\n");
		builder.append("</shycop-settings>");
		final File file = getSettingFile();
		final FileWriter fileWriter = new FileWriter(file);
		fileWriter.write(builder.toString().toCharArray());
		fileWriter.close();
		if (startProxy) {
			startProxy();
		} else {
			if (proxyServer.isRunning()) {
				proxyServer.closeSocket();
			}
		}
		if (enableFiltering) {
			ProxyServer.FLAG_RESOLVE_ADDRESSES = true;
		} else {
			ProxyServer.FLAG_RESOLVE_ADDRESSES = false;
		}

	}

	private static void startProxy() {
		try {
			if (proxyServer.isRunning()) {
				proxyServer.closeSocket();
			}
		} catch (Exception e) {
			//
		}
		proxyServer = new ProxyServer();
		proxyServer.doStart();
	}

}
